package org.shoukaiseki.aqoeous.config.dbconfig;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.shoukaiseki.aqoeous.constants.LoggerConstants;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.inject.Named;

import javax.sql.DataSource;

/**
 * org.shoukaiseki.aqoeous.config.dbconfig.DB1DataSourceConfig
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  19-2-11 下午2:28<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@Configuration
@MapperScan(basePackages = {DataBaseConfigConstants.DB1_PACKET_SELECTOR_BASE_PACKAGES_ONE, DataBaseConfigConstants.DB1_PACKET_SELECTOR_BASE_PACKAGES_TWO},sqlSessionFactoryRef = DataBaseConfigConstants.DB1_SQLSESSION_FACTORY)
public class DB1DataSourceConfig {

    final static Logger logger=DataBaseConfigConstants.logger;


    @Value(DataBaseConfigConstants.MAPPER_LOCATION)
    String mapperLocation;

    public DB1DataSourceConfig(){
    }


    @Bean(name = DataBaseConfigConstants.DB1_DATASOURCE, destroyMethod = "")
    @ConfigurationProperties(prefix = "sks.multiple.datasource.db1")
    public DataSource dataSource() {
        // 属性由springboot自动填写
        return new DruidDataSource();
    }


    @Bean(DataBaseConfigConstants.DB1_SQLSESSION_FACTORY)
    public SqlSessionFactory sqlSessionFactory(@Named(DataBaseConfigConstants.DB1_DATASOURCE) final DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));

        logger.debug("{}{}", LoggerConstants.PREFIX,"DB1DataSourceConfig.sqlSessionFactory");
        logger.debug("{}{}.url={}",LoggerConstants.PREFIX,"DB1DataSourceConfig",((DruidDataSource)dataSource).getUrl());

        return bean.getObject();
    }


    @Bean(name = DataBaseConfigConstants.DB1_TRANSACTIONMANAGER)
    public DataSourceTransactionManager transactionManager(@Named(DataBaseConfigConstants.DB1_DATASOURCE) final DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
